package com.uniriho.p2pconnectiontest;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;


public class WebSocketServerHelper {

    private WebSocketServer webSocketServer;

    public interface OnWebSocketServerListener {
        void onOpen(String remoteAddress);

        void onClose(int code, String reason, boolean remote);

        void onMessage(WebSocket conn, String message);
        void onStarted();

        void onError(Exception ex);
    }


    private OnWebSocketServerListener mOnWebSocketServerListener;

    public void setOnWebSocketListener(OnWebSocketServerListener webSocketServerListener) {
        if (webSocketServerListener == null) {
            return;
        }
        mOnWebSocketServerListener = webSocketServerListener;
    }

    public void start() {
        webSocketServer = new WebSocketServer(new InetSocketAddress("192.168.99.66",8088)) {
            @Override
            public void onOpen(WebSocket conn, ClientHandshake handshake) {
                ShowLogUtil.debug("onOpen:"+conn.getRemoteSocketAddress().getAddress());
                mOnWebSocketServerListener.onOpen(conn.getRemoteSocketAddress().getAddress().toString());
            }

            @Override
            public void onClose(WebSocket conn, int code, String reason, boolean remote) {
                ShowLogUtil.debug("onClose--->" + code);
                mOnWebSocketServerListener.onClose(code, reason, remote);
            }

            @Override
            public void onMessage(WebSocket conn, String message) {
                ShowLogUtil.debug("onMessage--->" + message);
                mOnWebSocketServerListener.onMessage(conn,message);
            }

            @Override
            public void onError(WebSocket conn, Exception ex) {
                mOnWebSocketServerListener.onError(ex);
                ShowLogUtil.debug("onError"+ex.toString());
            }

            @Override
            public void onStart() {
                mOnWebSocketServerListener.onStarted();
                ShowLogUtil.debug("onStart");
            }
        };

        webSocketServer.start();

    }

    public void stop() {
        if (webSocketServer == null) {
            return;
        }
        try {
            webSocketServer.stop();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public void send(String message) {
        if (webSocketServer == null) {
            return;
        }
        webSocketServer.broadcast(message);
    }
}
